package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.domain.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.util.Encrypt;

@Service
public class UserServiceImpl implements UserService{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	UserMapper userMapper;
	
	@Override
	public int userReg(User user) {
		logger.info("----服务userReg: ");
		//判断用户名是否可以注册
		List<User> users = new ArrayList<User>();
		users=userMapper.selectUsers();
		logger.info(users.toString());
		for (User u:users) {
			if((u.getUsername()).equals(user.getUsername()) || (u.getEmail()).equals(user.getEmail())) {
				logger.info("----用户名或邮箱已被使用");
				return 0;
			}
		}
		//可以，加密，否则返回信息
		user.setPwd(Encrypt.SHA512(user.getPwd()));
		//调用UserMapper，返回信息
		return userMapper.insertUser(user);
	}

	@Override
	public User userLogin(User user) {
		//查询所得的用户实体
		User dbUser = new User();
		//判断是有用户名还是邮箱
		logger.info(user.getEmail());
		logger.info(user.getUsername());
		if(user.getUsername()!=null) {
			dbUser = userMapper.selectUserByUsername(user);
		}
		else if(user.getEmail()!=null){
			dbUser = userMapper.selectUserByEmail(user);
		}
		else {
			return null;
		}
		//判断加密后的密码是否与数据库中的相同
		if(Encrypt.SHA512(user.getPwd()).equals(dbUser.getPwd())) {
			return dbUser;
		}
		else {
			return null;
		}
	}

	@Override
	public List<User> getFriendsByUser(User user) {
		logger.info("----UserServiceImpl.getFriendsByUser:");
		List<User> users = new ArrayList<User>();
		users = userMapper.selectFriend(user);
		return users;
	}

	@Override
	public List<User> getFollowByUser(User user) {
		logger.info("----UserServiceImpl.getFollowByUser:");
		List<User> users = new ArrayList<User>();
		users = userMapper.selectFollow(user);
		return users;
	}

	@Override
	public List<User> getBeFollowedByUser(User user) {
		logger.info("----UserServiceImpl.getBeFollowedByUser:");
		List<User> users = new ArrayList<User>();
		users = userMapper.selectBeFollowed(user);
		return users;
	}
	
	@Override
	public String getUsernameByUid(Integer uid) {
		logger.info("----UserServiceImpl.getUsernameByUid()");
		User user = userMapper.selectUserByUid(uid);
		if(user!=null) {
			return user.getUsername();
		}
		else {
			return "";
		}
	}

}
